<template>
	<view class="content">
	<view class="search-box" >
		<view class="category-search">
			<image src="/static/index-search.png" class="category-search-img"></image>
			<text class="category-search-text1">|</text>
			<text class="category-search-text"></text>
			<input type="text" v-model="val"   class="category-search-input" placeholder="请输入" @confirm="show,search" @blur="search"/>
		</view>
	</view>
	<!-- 热门搜索 -->
	<view class="search-keyword"  :class="bolShow?'none':'block'">
				<view class="leftBorder"></view>
				<text class="search-title">热门推荐</text>
				<view class="search-list" v-for="item in searchData" :key="item.id" >
					<text class="search-list-text" @click="addSearch" :data-a="item.name">{{item.name}}</text>
					<text class="clear"></text>
				</view>
			 </view>
			 	 <!-- 查询内容 -->
				 <view class="result" :class="bolShow?'block':'none'">
				 	<view class="navbar" :style="{position:headerPosition,top:headerTop}">
				 				<view class="nav-item" :class="{current: filterIndex === 0}" @click="tabClick(0)">
				 					综合排序
				 				</view>
				 				<view class="nav-item" :class="{current: filterIndex === 1}" @click="tabClick(1)">
				 					销量优先
				 				</view>
				 				<view class="nav-item" :class="{current: filterIndex === 2}" @click="tabClick(2)">
				 					<text>价格</text>
				 					<view class="p-box">
				 						<text :class="{active: priceOrder === 1 && filterIndex === 2}" class="yticon icon-shang"></text>
				 						<text :class="{active: priceOrder === 2 && filterIndex === 2}" class="yticon icon-shang xia"></text>
				 					</view>
				 				</view>
				 			</view>
				 			
				 			<!-- 商品列表 -->
				 			<view class="goods-list">
				 				<view v-for="(item, index) in goodsList" :key="index"
				 					class="goods-item" >
				 					  <view class="image-item-left" @click="navToDetailPage(item.id)">
				 						  <image :src="item.src" mode="aspectFill"></image>
				 					  </view>
				 					  <view class="image-item-right">
				 					      <text class="title" >{{item.name}}</text>
				 					      <view >
				 					  	      <text class="price">￥{{item.price}}</text>
				 					  	      <text class="sales">已售 {{item.numm}}</text>
				 							  <image src="../../static/tabbar/gouwuche1.png"  class="shoppingCar" @click="toggleSpec(item.id,item.price)"  alt="购物车图标"></image>
				 					      </view>
				 					  </view>
				 				</view>
				 			</view>
							
							
				 			<uni-load-more :status="loadingType"></uni-load-more>
							
							<!--  弹出层1  -->
							<!-- 规格-模态层弹窗 -->
							<view 
								class="popup spec" 
								:class="specClass"
								@touchmove.stop.prevent="stopPrevent"
								@click="toggleSpec"
							>
								<!-- 遮罩层 -->
								<view class="mask"></view>
								<view class="layer attr-content" @click.stop="stopPrevent">
									<view class="a-t">
										<image :src="spec.pic"></image>
										<view class="right">
											<text class="price">¥{{spec.price}}</text>
											<text class="stock">库存：{{spec.num}}件</text>
											<view class="selected">
												已选：
												<text class="selected-text" v-for="(sItem, sIndex) in specSelected" :key="sIndex">
													{{sItem.attr_name}}
												</text>
											</view>
										</view>
									</view>
									<view v-for="(item,index) in specList" :key="index" class="attr-list">
										<text>{{item.attr_name}}</text>
										<view class="item-list">
											<text 
												v-for="(childItem, childIndex) in specChildList" 
												v-if="childItem.attr_id === item.attr_id"
												:key="childIndex" class="tit"
												:class="{selected: childItem.selected}"
												@click="selectSpec(childIndex, childItem.attr_id)"
											>
												{{childItem.attr_name}}
											</text>
										</view>
									</view>
									<view class="buy-num">
										<text class="tit">购买数量</text>
										<view class="act-num">
											<text @click="numSub">-</text>
											<text>{{buyNum}}</text>
											<text @click="numAdd">+</text>
										</view>
									</view>
									
									<view class="btn">
										<text class="addCar" @click="addCar(msg.id,msg.norms,msg.price)">加入购物车</text>
										<text class="buy" @click="buy(msg.id,msg.price)">立即购买</text>
									</view>
									
								</view>
							</view>
							<!--  弹出层1end  -->
							
				 </view>

			 </view>
		
		
		
</template>
	

<script>
	 import url from '../../components/hosturl.js';
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	export default {
		data() {
			return {
					searchData:[],
					searchHistory:[{name:'aaa'}],
					val:'',
					headerPosition:"fixed",
					headerTop:"80rpx",
					loadingType: 'more', //加载更多状态
					filterIndex: 0, 
					cateId: 0, //已选三级分类id
					priceOrder: 0, //1 价格从低到高 2价格从高到低
					goodsList: [],
					cateList: [],
					bolShow:false,
					bolShow1:false,
					msg:{},
					number:1,
					arr:[],
					specClass: 'none',
					specList: [],//规格信息
					specChildList:[],
					spec:null, // 规格信息对像
					specSelected: [],
					buyNum:1,//购买数量
			}
		},
		onLoad(options){
			// #ifdef H5
			this.headerTop = document.getElementsByTagName('uni-page-head')[0].offsetHeight+'px';
			// #endif
			this.cateId = options.tid;
			this.loadData();
			uni.request({
				url:url+'/Main/getSearch',
				data:{},
				success:res=>{
					this.searchData=res.data.message;
				}
			})
		},
		onPageScroll(e){
			//兼容iOS端下拉时顶部漂移
			if(e.scrollTop>=0){
				this.headerPosition = "fixed";
			}else{
				this.headerPosition = "absolute";
			}
		},
		//下拉刷新
		onPullDownRefresh(){
			this.loadData('refresh');
		},
		//加载更多
		onReachBottom(){
			this.loadData();
		},
		methods: {
			//购买数量
			numSub(){
				if(this.buyNum>1){
					this.buyNum = this.buyNum-1;
				}else{
					uni.showToast({
						title:'购买数量不能为0'
					});
				}
				
			},
			numAdd(){
				this.buyNum = this.buyNum+1;
			},
			// 规格弹窗开关
			toggleSpec(id,price) {
				
				console.log('规格内容',this.specClass,id,price);
				this.msg.id = id;
				this.msg.price = price;
				if (this.specClass === 'show') {
					this.specClass = 'hide';
					setTimeout(() => {
						this.specClass = 'none';
					}, 250);
				} else if (this.specClass === 'none') {
					this.specClass = 'show';
					
					//获取规格接口信息！！！！！！
					uni.request({
						url:url+'/Commodity/getSpecifShopping',
						data:{
							id:15 //options.id
						},
						method:'get',
						success:(res)=>{
							var data = JSON.parse(res.data.message);
							
							this.spec = data[0];
							this.specList = data[0].attr_list;
							this.specChildList = data[0].attr_list;
							console.log('规格列表',this.specChildList);
							
						}
					});
					
					
					
				}
			},
			// 选择规格
			selectSpec(index, pid) {
				let list = this.specChildList;
				list.forEach(item => {
					if (item.pid === pid) {
						this.$set(item, 'selected', false);
					}
				})
			
				this.$set(list[index], 'selected', true);
				
				this.specSelected = [];
				list.forEach(item => {
					if (item.selected === true) {
						this.specSelected.push(item);
					}
				});
			
			},
			//添加购物车
			addCar(sid,attr,price){
				var num=String(this.buyNum);
				var token=uni.getStorageSync('token');
				var sid=String(sid);
				var price=String(price);
				console.log(sid,num,attr,price)
				uni.request({
					url:url+'/Shopping/putShoppingCar',
					method:'POST',
					data:{
						token,
						sid,
						num,
						attr,
						price
					},
					header: {
					        "Content-Type": "application/x-www-form-urlencoded"
					},
					success:res=>{
						console.log(res);
						if(res.data.msg=='添加成功'){
							uni.showToast({
							    title: '添加成功',
							    duration: 500
							});
							uni.switchTab({
								url:'/pages/shoppingcart/cart'
							});
						}else{
							uni.showToast({
							    title: '添加失败',
							    duration: 500
							});
						}
					}
				})
			},
			buy(id,price){
				var num=this.number;
				var attr = this.specSelected[0].attr_id;
				var obj={
					attr,
					id,
					price,
					num,
				};
				uni.navigateTo({
					url:'/pages/shoppingcart/createOrder?obj='+ encodeURIComponent(JSON.stringify(obj))
				});
				
			},
			
			// 切换显隐
			show(){
				this.bolShow=true;
			},
			search(){
				uni.request({
					url:url+'/Main/getDetailedProduct',
					data:{product:this.val},
					success:res=>{
					if(res.data.code==500){
						this.goodsList=[];
						uni.showToast({
						title: res.data.msg,
						duration: 500
						});
						}else{
						this.goodsList=res.data.message;
						this.$store.state.goodsList=res.data.message;
						}
					}
				})
				this.show();
			},
			// 点击热门搜索
			addSearch(e){
				this.val=e.currentTarget.dataset.a;
				uni.request({
					url:url+'/Main/getDetailedProduct',
					data:{product:this.val},
					success:res=>{
						if(res.data.code==500){
							this.goodsList=[];
							uni.showToast({
							    title: res.data.msg,
							    duration: 500
							});
						}else{
						this.goodsList=res.data.message;
						}
					}
				})
				this.show();
			},
			//加载商品 ，带下拉刷新和上滑加载
			async loadData(type='add', loading) {
				//没有更多直接返回
				if(type === 'add'){
					if(this.loadingType === 'nomore'){
						return;
					}
					this.loadingType = 'loading';
				}else{
					this.loadingType = 'more';
				}	
				//筛选，测试数据直接前端筛选了
				if(this.filterIndex === 0){
					
				}
				if(this.filterIndex === 1){
					this.goodsList = this.goodsList.sort((a,b)=>b.numm - a.numm);
				}
				if(this.filterIndex === 2){
					this.goodsList.sort((a,b)=>{
						if(this.priceOrder == 1){
							return a.price - b.price;
						}
						return b.price - a.price;
					})
				}
				
				//判断是否还有下一页，有是more  没有是nomore(测试数据判断大于20就没有了)
				this.loadingType  = this.goodsList.length > 20 ? 'nomore' : 'more';
				if(type === 'refresh'){
					if(loading == 1){
						uni.showLoading();
						setTimeout(function () {
						    uni.hideLoading();
						}, 800);
					}else{
						uni.stopPullDownRefresh();
					}
				}
			},
			//筛选点击
			tabClick(index){
				if(this.filterIndex === index && index !== 2){
					return;
				}
				this.filterIndex = index;
				if(index === 2){
					this.priceOrder = this.priceOrder === 1 ? 2: 1;
				}else{
					this.priceOrder = 0;
				}
				uni.pageScrollTo({
					duration: 300,
					scrollTop: 0
				})
				this.loadData('refresh', 1);
				uni.showLoading({
					title: '正在加载'
				})
			},
			//点击购物车图标，弹出底部蒙版层
			showTanchu(id,numm,name){
				uni.request({
					url:url+'/Commodity/getSpecifShopping',
					data:{id:Number(id)},
					success:res=>{
						console.log(res);
						var item=res.data.message[0];
						this.msg={id,name,src:item.cover_pic,price:item.price,stock:numm,norms:item.unit}
					}
				})
				this.bolShow1=true;
			},
			
			//详情
			navToDetailPage(id){
				uni.navigateTo({
					url: `/pages/classify/product?id=`+id
				})
			},
			stopPrevent(){},
			moveHandle(){}
		},
		components:{
		uniLoadMore
		}
	}
</script>

<style lang='scss'>
	page{background: #fff;}
	.search-box{background: #FFFFFF;height: 80rpx;left: 0;position: fixed;top: 0;width: 100%;z-index: 300;}
	.category-search{align-items: center;background: #f7f7f7;border-radius: 50rpx;display: flex;height: 60rpx;line-height:60rpx;width: 94%;margin: 10rpx 3%;justify-content: space-between;}
	.category-search-img{width: 40rpx;height: 40rpx;margin: 10rpx 20rpx;}
	.category-search-text{color: #8b8b8b;font-size: 26rpx;height: 60rpx;line-height: 60rpx;}
	.category-search-input{color: #8b8b8b; border-radius: 50rpx;height: 60rpx;line-height: 60rpx;font-size: 26rpx;width: 90%;text-indent: 10rpx;padding:0 10rpx;}
	.category-search-text1{color: #c8c8c8;font-size: 30rpx;}
	/* 热门搜索 */
	.search-keyword{background: #fff;height: 130rpx;margin: 110rpx  3% 0 3%;width: 94%;}
	.leftBorder{width: 10rpx;background: #1c2ab1;height: 30rpx;line-height: 40rpx;display: inline-block;}
		.search-title{font-size: 30rpx;line-height: 40rpx;height: 40rpx;padding-left: 20rpx;display: inline-block;background: #fff;position: relative;}
		.search-list-text{background: #f7f7f7;border-radius: 30rpx;color: #373737;font-size:26rpx;float: left;height: 50rpx;line-height: 50rpx;padding: 0 20rpx;margin: 10rpx 20rpx;}
	/* 搜索结果 */
	page, .result{background: #fff;}
		.result{padding-top: 96rpx;}
		.navbar{position: fixed;left: 0;top: var(--window-top);display: flex;width: 100%;height: 80rpx;background: #fff;box-shadow: 0 2rpx 10rpx rgba(0,0,0,.06);z-index: 10;.nav-item{flex: 1;display: flex;justify-content: center;align-items: center;height: 100%;font-size: 30rpx;color: $font-color-dark;position: relative;&.current{color: #3640a1;&:after{content: '';position: absolute;left: 50%;bottom: 0;transform: translateX(-50%);width: 60rpx;height: 0;border-bottom: 4rpx solid #3640a1;}}}
			.p-box{display: flex;flex-direction: column;.yticon{display: flex;align-items: center;justify-content: center;width: 30rpx;height: 14rpx;line-height: 1;margin-left: 4rpx;font-size: 26rpx;color: #888;&.active{olor: $base-color;}}.xia{transform: scaleY(-1);}}}
	/*  商品列表 */ 
	.goods-list{ background: #ddd;display:flex;flex-direction: column;margin-top: 70rpx;}
	.goods-item{ background: #fff;display:flex;margin-top: 20rpx;padding:30rpx;width: 100%; }
	/* 商品图片 */ 
	.image-item-left{ height: 200rpx;margin-right: 20rpx;width: 200rpx; }
	.image-item-left image{ height: 200rpx;width: 200rpx;opacity: 1;}
	.image-item-right{ display: flex; flex: 2;flex-direction: column; height: 200rpx;justify-content: space-between;overflow: hidden;}
	/* 商品名 */ 
	.title{ color: #333; font-size: 30rpx;margin-top: 10rpx;}
	/* 单价 */ 
	.price{font-size: 28rpx;margin-right: 20rpx;}
	/* 销量 */
	.sales{color: #8b8b8b;font-size: 28rpx;}
	/* 购物车图标 */ 
	.image-item-right image{height: 40rpx;float: right;overflow: hidden;width: 40rpx;}
	/* 控制显隐效果 */
	.none{display: none;}
	.block{display: block;}

/* 购买数量 */
.buy-num { height:100rpx;display: flex;justify-content:space-between;border-top:1px #ddd solid;align-items:center;padding-top:30rpx; }
.buy-num .tit { line-height:100rpx; }
.buy-num .act-num { display: flex; }
.buy-num .act-num text { height:78rpx;height:78rpx;width:78rpx;justify-items:center;line-height: center;display: flex;justify-content: center;align-items: center;border:1px #ddd solid;font-size:40rpx;background:#fafafa; }
.buy-num .act-num text:nth-child(2) { width:120rpx; }
	/* 规格选择弹窗 */
	.attr-content {
		padding: 10upx 30upx;

		.a-t {
			display: flex;

			image {
				width: 170upx;
				height: 170upx;
				flex-shrink: 0;
				margin-top: -40upx;
				border-radius: 8upx;
				;
			}

			.right {
				display: flex;
				flex-direction: column;
				padding-left: 24upx;
				font-size: $font-sm + 2upx;
				color: $font-color-base;
				line-height: 42upx;

				.price {
					font-size: $font-lg;
					color: $uni-color-primary;
					margin-bottom: 10upx;
				}

				.selected-text {
					margin-right: 10upx;
				}
			}
		}

		.attr-list {
			display: flex;
			flex-direction: column;
			font-size: $font-base + 2upx;
			color: $font-color-base;
			padding-top: 30upx;
			padding-left: 10upx;
		}

		.item-list {
			padding: 20upx 0 0;
			display: flex;
			flex-wrap: wrap;

			text {
				display: flex;
				align-items: center;
				justify-content: center;
				background: #eee;
				margin-right: 20upx;
				margin-bottom: 20upx;
				border-radius: 100upx;
				min-width: 60upx;
				height: 60upx;
				padding: 0 20upx;
				font-size: $font-base;
				color: $font-color-dark;
			}

			.selected {
				background: #fbebee;
				color: $uni-color-primary;
			}
		}
	}

	/*  弹出层 */
	.popup {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 99;

		&.show {
			display: block;

			.mask {
				animation: showPopup 0.2s linear both;
			}

			.layer {
				animation: showLayer 0.2s linear both;
			}
		}

		&.hide {
			.mask {
				animation: hidePopup 0.2s linear both;
			}

			.layer {
				animation: hideLayer 0.2s linear both;
			}
		}

		&.none {
			display: none;
		}

		.mask {
			position: fixed;
			top: 0;
			width: 100%;
			height: 100%;
			z-index: 1;
			background-color: rgba(0, 0, 0, 0.4);
		}

		.layer {
			position: fixed;
			z-index: 99;
			bottom: 0;
			width: 100%;
			min-height: 40vh;
			border-radius: 10upx 10upx 0 0;
			background-color: #fff;

			.btn {
				height: 66upx;
				line-height: 66upx;
				border-radius: 100upx;
				background: $uni-color-primary;
				font-size: $font-base + 2upx;
				color: #fff;
				margin: 30upx auto 20upx;
				display:flex;
				
				text {
					display: block;
					flex:1;
					text-align: center;
				}
				
			}
		}

		@keyframes showPopup {
			0% {
				opacity: 0;
			}

			100% {
				opacity: 1;
			}
		}

		@keyframes hidePopup {
			0% {
				opacity: 1;
			}

			100% {
				opacity: 0;
			}
		}

		@keyframes showLayer {
			0% {
				transform: translateY(120%);
			}

			100% {
				transform: translateY(0%);
			}
		}

		@keyframes hideLayer {
			0% {
				transform: translateY(0);
			}

			100% {
				transform: translateY(120%);
			}
		}
	}

	/* 底部操作菜单 */
	.page-bottom {
		position: fixed;
		left: 30upx;
		bottom: 30upx;
		z-index: 95;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 690upx;
		height: 100upx;
		background: rgba(255, 255, 255, .9);
		box-shadow: 0 0 20upx 0 rgba(0, 0, 0, .5);
		border-radius: 16upx;

		.p-b-btn {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			font-size: $font-sm;
			color: $font-color-base;
			width: 96upx;
			height: 80upx;

			.yticon {
				font-size: 40upx;
				line-height: 48upx;
				color: $font-color-light;
			}

			&.active,
			&.active .yticon {
				color: $uni-color-primary;
			}

			.icon-fenxiang2 {
				font-size: 42upx;
				transform: translateY(-2upx);
			}

			.icon-shoucang {
				font-size: 46upx;
			}
		}

		.action-btn-group {
			display: flex;
			height: 76upx;
			border-radius: 100px;
			overflow: hidden;
			box-shadow: 0 20upx 40upx -16upx #a387eb;
			box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
			background: linear-gradient(to right, #ffac30, #a387eb, #F56C6C);
			margin-left: 20upx;
			position: relative;

			&:after {
				content: '';
				position: absolute;
				top: 50%;
				right: 50%;
				transform: translateY(-50%);
				height: 28upx;
				width: 0;
				border-right: 1px solid rgba(255, 255, 255, .5);
			}

			.action-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 180upx;
				height: 100%;
				font-size: $font-base;
				padding: 0;
				border-radius: 0;
				background: transparent;
			}
		}
	}
</style>
